package com.sghj.config.realm;

import com.sghj.SysPermission.entity.SysUser;
import com.sghj.SysPermission.service.SysUserShiroService;
import com.sghj.utils.UserUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author xrx
 * @Date 2022/2/14
 * @apiNote
 */
public class myRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(myRealm.class);

    @Autowired
    private SysUserShiroService userService;


    /**
     * 权限
     * 配置当前用户的权限有哪些
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //1.获取当前用户
        SysUser user = UserUtils.getLoginUser();
        //SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        //SysUser user = (SysUser) principalCollection.asList().get(0);
        //如果是管理员
        if (user.getUserType().equals("1"))
        {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        }else {
            //普通用户
            Set<String> userMenu = userService.getUserMenu(user.getSysUserId());
            Set<String> roles =userService.getUserRoles(user.getSysUserId());
            info.addRoles(roles);
            info.addStringPermissions(userMenu);
        }
        return info;
    }

    /**
     * 认证   登录(验证逻辑在这里)
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = "";
        if (token.getPassword()!=null){
            password = new String(token.getPassword());
        }
        SysUser user = null;
        //只验证账号存在的问题
         user= userService.handleLogin(username,password);

        //shiro自动会做密码检测
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPwd(), ByteSource.Util.bytes("zjcq666"),getName());

        return simpleAuthenticationInfo;
    }


}
